package com.example;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.dao.CustomerDao;
import com.example.dto.Customer;

/**
 * Servlet implementation class LoginServlet
 */

public class LoginServlet extends HttpServlet {

	CustomerDao customerDao = null;
	private static final long serialVersionUID = 1L;

	@Override
	public void init() throws ServletException {

		customerDao = new CustomerDao();

	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");

		String userNameInput = request.getParameter("userName");

		String passwordInput = request.getParameter("password");

		Customer custmomer = customerDao.loadCustomer(userNameInput.trim(),
				passwordInput.trim());
		PrintWriter writer = response.getWriter();
		if (custmomer != null) {

			writer.println("<html><h1> This is from Login Servlet </h1> </html>");
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("home.jsp");

			Cookie cookie = new Cookie("user", custmomer.getFirstName());

			cookie.setMaxAge(20*60);

			response.addCookie(cookie);

			request.setAttribute("firstName", custmomer.getFirstName());
			dispatcher.forward(request, response);

		} else {
			response.sendRedirect("registration.html");
		}

		writer.close();

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}
